package com.framework.controller.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.tools.ant.util.Base64Converter;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.Base64;
import com.framework.annotation.SystemLog;
import com.framework.controller.index.BaseController;
import com.framework.entity.ButtomFormMap;
import com.framework.entity.ConsoleuserFormMap;
import com.framework.entity.FileFormMap;
import com.framework.entity.FuncFileFormMap;
import com.framework.entity.Params;
import com.framework.entity.ProductFormMap;
import com.framework.entity.ProductTreeFormMap;
import com.framework.entity.ProductTreeFormMap;
import com.framework.entity.ResUserFormMap;
import com.framework.entity.UserRoleFormMap;
import com.framework.entity.view.FuncFileViewFormMap;
import com.framework.mapper.ProductTreeMapper;
import com.framework.mapper.ResourcesMapper;
import com.framework.plugin.PageView;
import com.framework.plugin.token.Token;
import com.framework.util.Base64Uitl;
import com.framework.util.Common;
import com.framework.util.TreeObject;
import com.framework.util.TreeUtil;

import net.sf.json.JSONArray;

/**
 * 
 * @author framework
 * @date 2015-11-19
 * @Email: g5874589652@126.com
 * @version 4.0v
 */
@Controller
@RequestMapping("/producttree/")
public class ProductTreeController extends BaseController {
	@Inject
	private ProductTreeMapper productTreeMapper;

	/**
	 * @param model
	 *            存放返回界面的model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("treelists")
	public ProductTreeFormMap findByPage(Model model) {
		ProductTreeFormMap productTreeFormMap = getFormMap(ProductTreeFormMap.class);
		String order = " order by parentId asc";
		productTreeFormMap.put("$orderby", order);
		List<ProductTreeFormMap> mps = productTreeFormMap.findByNames();
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (ProductTreeFormMap map : mps) {
			TreeObject ts = new TreeObject();
			Common.flushObject(ts, map);
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0);
		productTreeFormMap = new ProductTreeFormMap();
		productTreeFormMap.put("treelists", ns);
		return productTreeFormMap;
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public ProductTreeFormMap findByPage(String draw, String pageSize, String start) throws Exception {
		ProductTreeFormMap productFormMap = getFormMap(ProductTreeFormMap.class);
		List<ProductTreeFormMap> mps;
		productFormMap.put("$orderby", "order by create_date asc");
		if (productFormMap.containsKey("name")) {
			String name = productFormMap.getStr("name");
			productFormMap.put("$search", name);
			productFormMap.remove("name");
			productFormMap.put("keyCloumn",  getKeyCloumn());
			productFormMap = toFormMap(productFormMap, draw, "100", start);
			mps=productFormMap.findByNames_Page();

		}
		mps = productFormMap.findByNames();
		// 填充
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (ProductTreeFormMap map : mps) {
			TreeObject ts = new TreeObject();
			Common.flushObject(ts, map);
			list.add(ts);
		}

		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0);
		ProductTreeFormMap productTreeFormMap = new ProductTreeFormMap();
		productTreeFormMap.put("treelists", ns);
		return productTreeFormMap;
	}

	@ResponseBody
	@RequestMapping("reslists")
	public List<TreeObject> reslists(Model model) throws Exception {
		ProductTreeFormMap productTreeFormMap = getFormMap(ProductTreeFormMap.class);
		List<ProductTreeFormMap> mps = productTreeFormMap.findByWhere();
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (ProductTreeFormMap map : mps) {
			TreeObject ts = new TreeObject();
			Common.flushObject(ts, map);
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0, "　");
		return ns;
	}

	// 验证方法
	@ResponseBody
	@RequestMapping("priceisNum")
	public boolean priceisNum(String name) {
		ProductTreeFormMap formMap = getFormMap(ProductTreeFormMap.class);
		if (!formMap.containsKey("price")) {
			return false;
		}

		String price = formMap.getStr("price");
		if (!Common.isNumeric(price)) {
			return false;
		}
		return true;
	}

	@ResponseBody
	@RequestMapping("listParent")
	public List<ProductFormMap> listParent(Model model) throws Exception {
		ProductFormMap productFormMap = getFormMap(ProductFormMap.class);
		productFormMap.put("parentId", 0);
		List<ProductFormMap> list = productFormMap.findByNames();
		return list;
	}

	/**
	 * @param model
	 *            存放返回界面的model
	 * @return
	 */
	@RequestMapping("list")
	public String list(Model model) {
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/system/producttree/list";
	}

	/**
	 * 跳转到修改界面
	 * 
	 * @param model
	 * @param resourcesId
	 *            修改产品信息ID
	 * @return
	 */
	@RequestMapping("editUI")
	public String editUI(Model model) {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			FuncFileViewFormMap funcFileViewFormMap = new FuncFileViewFormMap();
			funcFileViewFormMap = funcFileViewFormMap.findById(id);
			model.addAttribute("funcFileViewFormMap", funcFileViewFormMap);
		}
		return Common.BACKGROUND_PATH + "/system/producttree/edit";
	}

	/**
	 * 跳转到新增界面
	 * 
	 * @return
	 */
	@RequestMapping("addUI")
	public String addUI(Model model) {
		return Common.BACKGROUND_PATH + "/system/producttree/add";
	}

	@RequestMapping("showUI")
	// @Token(save=true)
	public String showUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/producttree/showUI";
	}

	/**
	 * 权限分配页面
	 * 
	 * @author framework Email：g5874589652@126.com date：2015-4-14
	 * @param model
	 * @return
	 */
	@RequestMapping("permissions")
	public String permissions(Model model) {
		ProductTreeFormMap productTreeFormMap = getFormMap(ProductTreeFormMap.class);
		List<ProductTreeFormMap> mps = productTreeFormMap.findByWhere();
		List<TreeObject> list = new ArrayList<TreeObject>();
		for (ProductTreeFormMap map : mps) {
			TreeObject ts = new TreeObject();
			Common.flushObject(ts, map);
			list.add(ts);
		}
		TreeUtil treeUtil = new TreeUtil();
		List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0);
		model.addAttribute("permissions", ns);
		return Common.BACKGROUND_PATH + "/system/producttree/permissions";
	}

	/**
	 * 添加产品
	 * 
	 * @param producttree
	 * @return Map
	 * @throws Exception
	 */
	@RequestMapping("addForm")
	@ResponseBody
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "产品管理-新增产品") // 凡需要处理业务逻辑的.都需要记录操作日志
	// @Token(remove=true)
	public String addForm() throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		hashMap.remove("token");

		ProductTreeFormMap productTreeFormMap = getMapformDataMap(ProductTreeFormMap.class, hashMap);
		productTreeFormMap = productTreeFormMap.save();// 保存老大
		String id = productTreeFormMap.getStr("id");
		// 保存产品,以及关系
		for (int i = 0; i < 10; i++) {
			Object specification = hashMap.get("standard[" + i + "][specifications]");
			Object spec_value = hashMap.get("standard[" + i + "][spec_values]");
			Object price = hashMap.get("standard[" + i + "][prices]");
			Object stock = hashMap.get("standard[" + i + "][stocks]");

			String path = Common.getContextRealPath();

			if (specification == null || spec_value == null || price == null || stock == null) {
				break;
			} else {
				if (!Common.isNumeric(price.toString())) {
					productTreeFormMap.deleteById(id);
					return "price is not number";
				}
				if (!Common.isNumeric(stock.toString())) {
					productTreeFormMap.deleteById(id);
					return "stock is not number";
				}
				productTreeFormMap.remove("id");
				productTreeFormMap.remove("remark");
				productTreeFormMap.put("parentId", id);
				productTreeFormMap.put("specification", specification);
				productTreeFormMap.put("spec_value", spec_value);
				productTreeFormMap.put("price", price);
				productTreeFormMap.put("stock", stock);
				productTreeFormMap.save();
			}
		}

		// 保存文件,以及关系
		for (int i = 0; i < 10; i++) {
			Object pic = hashMap.get("picture[" + i + "][src]");
			if (pic != null) {
				String filename = hashMap.get("picture[" + i + "][name]").toString();
				String picStr = pic.toString();
				saveFile(picStr, id, filename);
			} else {
				break;
			}
		}

		return "success";
	}
	
	/**
	 * 添加产品
	 * 
	 * @param producttree
	 * @return Map
	 * @throws Exception
	 */
	@RequestMapping("editForm")
	@ResponseBody
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "产品管理-新增产品") // 凡需要处理业务逻辑的.都需要记录操作日志
	// @Token(remove=true)
	public String editForm() throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		hashMap.remove("token");
		ProductTreeFormMap productTreeFormMap = getMapformDataMap(ProductTreeFormMap.class, hashMap);
		productTreeFormMap = productTreeFormMap.update();// 保存老大
		String id = productTreeFormMap.getStr("id");
		// 保存产品,以及关系
		for (int i = 0; i < 10; i++) {
			Object child_id=hashMap.get("standard[" + i + "][id]");
			Object specification = hashMap.get("standard[" + i + "][specifications]");
			Object spec_value = hashMap.get("standard[" + i + "][spec_values]");
			Object price = hashMap.get("standard[" + i + "][prices]");
			Object stock = hashMap.get("standard[" + i + "][stocks]");

			if (specification != null && spec_value != null && price != null &&stock != null && child_id!=null) {
				//这是修改
				productTreeFormMap.remove("remark");
				productTreeFormMap.put("id", child_id);
				productTreeFormMap.put("parentId", id);
				productTreeFormMap.put("specification", specification);
				productTreeFormMap.put("spec_value", spec_value);
				productTreeFormMap.put("price", price);
				productTreeFormMap.put("stock", stock);
				productTreeFormMap.update();
			} else if (specification != null && spec_value != null && price != null &&stock != null && child_id==null) {
				//那么要新增
				productTreeFormMap.remove("remark");
				productTreeFormMap.remove("id");
				productTreeFormMap.put("parentId", id);
				productTreeFormMap.put("specification", specification);
				productTreeFormMap.put("spec_value", spec_value);
				productTreeFormMap.put("price", price);
				productTreeFormMap.put("stock", stock);
				productTreeFormMap.save();
			}else {
				System.out.println("属性丢失");
			}
		}
		
		new FuncFileFormMap().deleteByAttribute("func_id", id);
		// 保存文件,以及关系
		for (int i = 0; i < 10; i++) {
			Object pic_id = hashMap.get("picture[" + i + "][id]");
			Object pic_src = hashMap.get("picture[" + i + "][src]");
			if (pic_id!=null&& !"WU_FILE_0".equals(pic_id)) {
				FuncFileFormMap funcFileFormMap=new FuncFileFormMap();
				funcFileFormMap.put("func_id", id);
				funcFileFormMap.put("file_id", pic_id);
				funcFileFormMap.save();
			}else if (pic_src!=null && "WU_FILE_0".equals(pic_id)) {
				//新增
				String filename = hashMap.get("picture[" + i + "][name]").toString();
				String picStr = pic_src.toString();
				saveFile(picStr, id, filename);
			}else {
				break;
			}
		}

		return "success";
	}
	
	/**
	 * 查找产品
	 * 
	 * @param producttree
	 * @return Map
	 * @throws Exception
	 */
	public ProductTreeFormMap findForm() throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		FuncFileViewFormMap formMap = getMapformDataMap(FuncFileViewFormMap.class, hashMap);
		ProductTreeFormMap productTreeFormMap=getMapformDataMap(ProductTreeFormMap.class, hashMap);
		List<FuncFileViewFormMap> funcFileViewFormMaps=formMap.findByNames();
		
		ArrayList<Object> file_nameList=new ArrayList<>();
		ArrayList<Object> file_pathList=new ArrayList<>();
		ArrayList<Object> file_idList=new ArrayList<>();
		ArrayList<String> file_streamList=new ArrayList<>();
		for (FuncFileViewFormMap funcFileViewFormMap : funcFileViewFormMaps) {
			String base64Str = null;
			Object file_id=funcFileViewFormMap.get("file_id");
			Object file_name=funcFileViewFormMap.get("file_name");
			Object file_path=funcFileViewFormMap.get("file_path");
			byte[] file_stream=(byte[]) funcFileViewFormMap.get("file_stream");
			
			if (file_stream!=null) {
				base64Str=new String(file_stream);
				Base64Uitl.GenerateImage(base64Str,file_path.toString());
				file_streamList.add("data:image/"+funcFileViewFormMap.get("file_type")+";base64,"+base64Str);
			}
			file_nameList.add(file_name);
			file_pathList.add(file_path);
			file_idList.add(file_id);
		}
		
		if (funcFileViewFormMaps.size()>0) {
			String id=formMap.get("id").toString();
			
			productTreeFormMap=productTreeFormMap.findById(id);
			List<FuncFileViewFormMap> list=formMap.findByAttribute("parentId", id);
			
			productTreeFormMap.put("file_idList", file_idList);
			productTreeFormMap.put("file_nameList", file_nameList);
			productTreeFormMap.put("file_pathList", file_pathList);
			productTreeFormMap.put("file_streamList", file_streamList);
			productTreeFormMap.put("childList",JSONArray.fromObject(list) );
			
		}
		return productTreeFormMap;
	}
	
	/**
	 * 查找产品
	 * 
	 * @param producttree
	 * @return Map
	 * @throws Exception
	 */
	@RequestMapping("editFormUI")
	@SystemLog(module = "系统管理", methods = "产品管理-新增产品") // 凡需要处理业务逻辑的.都需要记录操作日志
	// @Token(remove=true)
	public String editFormUI(Model model) throws Exception {
		ProductTreeFormMap productTreeFormMap=findForm();
		model.addAttribute("formMap", productTreeFormMap);
		return Common.BACKGROUND_PATH + "/system/producttree/editFormUI";
	}
	

	private void saveFile(String picStr, String id, String filename) throws Exception {
		FileFormMap fileFormMap = new FileFormMap();
		FuncFileFormMap funcFileFormMap = new FuncFileFormMap();
		int index = filename.lastIndexOf(".");
		String type = filename.substring(index + 1);
		fileFormMap.put("file_name", filename);

		FileFormMap fileFormMap2 = fileFormMap.findbyFrist();
		fileFormMap.put("file_name", filename);
		
		int beginIndex=picStr.indexOf("/9j/");
		picStr=picStr.substring(beginIndex);
		String path = Base64Uitl.GenerateImage(picStr, Common.getContextRealPath() + "images", filename);// 保存的进入数据库的同时，在本地生成图片。

		fileFormMap.put("file_path", path);
		fileFormMap.put("file_type", type);
		fileFormMap.put("file_stream", picStr.getBytes());
		fileFormMap = fileFormMap.save();

		funcFileFormMap.put("func_id", id);
		funcFileFormMap.put("file_id", fileFormMap.get("id"));
		funcFileFormMap.save();
	}

	/**
	 * 添加产品
	 * 
	 * @param producttree
	 * @return Map
	 * @throws Exception
	 */
	@RequestMapping("addEntity")
	@ResponseBody
	@Token(remove = true)
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "产品管理-新增产品") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String addEntity() throws Exception {
		ProductTreeFormMap productTreeFormMap = getFormMap(ProductTreeFormMap.class);
		productTreeFormMap.save();
		return "success";
	}

	/**
	 * 更新产品
	 * 
	 * @param model
	 * @param Map
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "产品管理-修改产品") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity(Model model) throws Exception {
		FuncFileViewFormMap functionViewFormMap = getFormMap(FuncFileViewFormMap.class);
		ProductTreeFormMap productTreeFormMap = new ProductTreeFormMap();
		if (!functionViewFormMap.isEmpty()) {
			HashMap<String, Object> hashMap = (HashMap<String, Object>) functionViewFormMap.clone();
			productTreeFormMap = getMapformDataMap(ProductTreeFormMap.class, hashMap);

			if ("2".equals(productTreeFormMap.get("type"))) {
				productTreeFormMap.put("description", Common.htmltoString(productTreeFormMap.get("description") + ""));
			}
			Object o = productTreeFormMap.get("ishide");
			if (null == o) {
				productTreeFormMap.put("ishide", "0");
			}
			
			
			if (Common.findUserSession()!=null) {
				ConsoleuserFormMap consoleuserFormMap=(ConsoleuserFormMap) Common.findUserSession();
				String accountName=consoleuserFormMap.getStr("accountName");
				
				productTreeFormMap.put("alterman", accountName);
			}
			
			productTreeFormMap.update();
			return "success";
		}
		return "failed";
	}

	/**
	 * 根据ID删除产品
	 * 
	 * @param model
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("deleteEntity")
	@SystemLog(module = "系统管理", methods = "产品管理-删除产品") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity(Model model) throws Exception {
		String[] ids = getParaValues("ids");
		for (String id : ids) {
			ProductTreeFormMap productTreeFormMap = new ProductTreeFormMap();
			productTreeFormMap.deleteById(id);
		}
		;
		return "success";
	}

	@RequestMapping("sortUpdate")
	@ResponseBody
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	public String sortUpdate(Params params) throws Exception {
		List<String> ids = params.getId();
		List<String> es = params.getRowId();
		List<ProductTreeFormMap> maps = new ArrayList<ProductTreeFormMap>();
		ProductTreeFormMap map = null;
		for (int i = 0; i < ids.size(); i++) {
			map = new ProductTreeFormMap();
			map.put("id", ids.get(i));
			map.put("level", es.get(i));
			maps.add(map);
		}
		ProductTreeFormMap.mapper().updateSortOrder(maps);
		return "success";
	}

	@ResponseBody
	@RequestMapping("findRes")
	public List<ProductTreeFormMap> findUserRes() {
		ProductTreeFormMap productTreeFormMap = getFormMap(ProductTreeFormMap.class);
		List<ProductTreeFormMap> rs = ProductTreeFormMap.mapper().findRes(productTreeFormMap);
		return rs;
	}

	@ResponseBody
	@RequestMapping("addUserRes")
	@Transactional(readOnly = false) // 需要事务操作必须加入此注解
	@SystemLog(module = "系统管理", methods = "用户管理/组管理-修改权限") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String addUserRes() throws Exception {
		String userId = "";
		String u = getPara("userId");
		String g = getPara("roleId");
		if (null != u && !Common.isEmpty(u.toString())) {
			userId = u.toString();
		} else if (null != g && !Common.isEmpty(g.toString())) {
			List<UserRoleFormMap> gs = new UserRoleFormMap().findByAttribute("roleId", g.toString());
			for (UserRoleFormMap ug : gs) {
				userId += ug.get("userId") + ",";
			}
		}
		userId = Common.trimComma(userId);
		String[] users = userId.split(",");
		ResUserFormMap resUserFormMap = new ResUserFormMap();
		for (String uid : users) {
			resUserFormMap.deleteByAttribute("userId", uid);
			String[] s = getParaValues("resId[]");
			List<ResUserFormMap> resUserFormMaps = new ArrayList<ResUserFormMap>();
			for (String rid : s) {
				resUserFormMap = new ResUserFormMap();
				resUserFormMap.put("resId", rid);
				resUserFormMap.put("userId", uid);
				resUserFormMaps.add(resUserFormMap);

			}
			resUserFormMap.batchSave(resUserFormMaps);
		}
		return "success";
	}

	/**
	 * 验证产品是否存在
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist(String name, String resKey) {
		ProductTreeFormMap productTreeFormMap = getFormMap(ProductTreeFormMap.class);
		List<ProductTreeFormMap> r = productTreeFormMap.findByNames();
		if (r.size() == 0) {
			return true;
		} else {
			return false;
		}
	}

	@ResponseBody
	@RequestMapping("findByButtom")
	public List<ButtomFormMap> findByButtom() {
		return productTreeMapper.findByWhere(new ButtomFormMap());
	}

}